package com.zuorenke.redis;

import com.zuorenke.serialize.DefaultSerializableAdapter;
import com.zuorenke.serialize.SerializableAdapter;
import com.zuorenke.vertx.config.RedisProperties;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author Z.R.K
 * @description
 * @create 2019-04-11 16:39:58
 **/
@Configuration
public class RedisConfig {
	
	@Resource
	private RedisProperties redisProperties;
	
	@Resource
	private SerializableAdapter serializableAdapter;
	
	@Bean
	public GenericObjectPoolConfig rcPoolConf() {
		GenericObjectPoolConfig rcPoolConf = new GenericObjectPoolConfig();
		rcPoolConf.setMaxWaitMillis(redisProperties.getPoolMaxWait());
		rcPoolConf.setMaxTotal(redisProperties.getPoolMaxTotal());
		rcPoolConf.setMinIdle(redisProperties.getPoolMinIdle());
		rcPoolConf.setMaxIdle(redisProperties.getPoolMaxIdle());
		rcPoolConf.setTestOnBorrow(true);
		return rcPoolConf;
	}

	@Bean
	public JedisClusterFactory rcFactory() {
		JedisClusterFactory factory = new JedisClusterFactory();
		factory.setHostAndPortConf(redisProperties.getClusterNodes());
		factory.setTimeout(redisProperties.getTimeout());
		factory.setMaxRedirections(redisProperties.getPoolMaxRedirections());
		factory.setRcPoolConf(this.rcPoolConf());
		return factory;
	}

	@Bean
	public GenericObjectPool rcPool() {
		GenericObjectPool pool = new GenericObjectPool(this.rcFactory());
		pool.setConfig(this.rcPoolConf());
		return pool;
	}

	@Bean
	public JedisClusterClient jedisClusterClient() {
		JedisClusterClient client = new JedisClusterClient();
		client.setRcPool(this.rcPool());
		client.setSerializer(serializableAdapter);
		return client;
	}

}